import React, { useState } from "react";
import { Button, Descriptions, message, Form, Input } from "antd";
import { EditOutlined, SaveOutlined, CloseOutlined } from "@ant-design/icons";
import "./index.css";
import { updateMyUserUsingPost } from "@/api/userController";
import { setLoginUser } from "@/stores/loginUser";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/stores";

interface Props {
    user: API.LoginUserVO;
}

/**
 * 用户个人资料组件
 * @param props
 * @constructor
 */
const UserInfo = (props: Props) => {
    const { user } = props;
    const [isEditing, setIsEditing] = useState(false);
    const [form] = Form.useForm();
    const dispatch = useDispatch<AppDispatch>();

    // 处理编辑按钮点击事件
    const handleEditClick = () => {
        // 使用用户数据初始化表单
        form.setFieldsValue({
            phoneNumber: user.phoneNumber,
            email: user.email,
            grade: user.grade,
            workExperience: user.workExperience,
            expertiseDirection: user.expertiseDirection,
        });
        setIsEditing(true);
    };

    // 处理取消编辑
    const handleCancel = () => {
        setIsEditing(false);
    };

    // 处理保存表单
    const handleSave = () => {
        form
            .validateFields()
            .then(async (values: API.UserUpdateMyRequest) => {
                try {
                    await updateMyUserUsingPost(values);
                    message.success("资料更新成功");
                    // 更新Redux中的用户信息
                    dispatch(setLoginUser({ ...user, ...values }));
                } catch (error: any) {
                    message.error("更新失败，" + error.message);
                }
                setIsEditing(false);
            });
    };

    // 表单字段配置
    const formItems = [
        {
            name: "phoneNumber",
            label: "手机号",
            rules: [{ required: true, message: "请输入手机号" }]
        },
        {
            name: "email",
            label: "邮箱",
            rules: [{ required: true, message: "请输入邮箱" }]
        },
        {
            name: "grade",
            label: "年级",
            rules: [{ required: true, message: "请输入年级" }]
        },
        {
            name: "workExperience",
            label: "工作经验"
        },
        {
            name: "expertiseDirection",
            label: "擅长方向"
        },
    ];

    return (
        <div style={{ marginTop: 20, position: "relative" }}>
            {/* 编辑/保存按钮 - 右上角 */}
            {isEditing ? (
                <div style={{ position: "absolute", top: -10, right: 0, zIndex: 1 }}>
                    <Button
                        type="primary"
                        icon={<SaveOutlined />}
                        onClick={handleSave}
                        style={{ marginRight: 8 }}
                    >
                        提交
                    </Button>
                    <Button icon={<CloseOutlined />} onClick={handleCancel}>
                        取消
                    </Button>
                </div>
            ) : (
                <Button
                    type="primary"
                    icon={<EditOutlined />}
                    onClick={handleEditClick}
                    style={{
                        position: "absolute",
                        top: -10,
                        right: 0,
                        zIndex: 1,
                    }}
                >
                    修改资料
                </Button>
            )}

            {isEditing ? (
                // 编辑模式 - 显示行内表单
                <div className="inline-form-container">
                    <Form form={form}>
                        {formItems.map((item) => (
                            <div key={item.name} className="form-field-row">
                                <span className="form-label">{item.label}：</span>
                                <Form.Item
                                    name={item.name}
                                    rules={item.rules}
                                    style={{ margin: 0, display: "inline-block", flexGrow: 1 }}
                                >
                                    <Input
                                        placeholder={`请输入${item.label}`}
                                        className="inline-input"
                                        style={{ width: "100%" }}
                                    />
                                </Form.Item>
                            </div>
                        ))}
                    </Form>
                </div>
            ) : (
                // 查看模式 - 显示描述信息
                <Descriptions
                    column={1}
                    bordered={false}
                    size="small"
                    labelStyle={{
                        fontWeight: "bold",
                        width: "80px",
                        paddingRight: 8,
                    }}
                    contentStyle={{ paddingLeft: 0 }}
                >
                    <Descriptions.Item label="手机号">
                        {user.phoneNumber || "未填写"}
                    </Descriptions.Item>
                    <Descriptions.Item label="邮箱">
                        {user.email || "未填写"}
                    </Descriptions.Item>
                    <Descriptions.Item label="年级">
                        {user.grade || "未填写"}
                    </Descriptions.Item>
                    <Descriptions.Item label="工作经验">
                        {user.workExperience || "未填写"}
                    </Descriptions.Item>
                    <Descriptions.Item label="擅长方向">
                        {user.expertiseDirection || "未填写"}
                    </Descriptions.Item>
                </Descriptions>
            )}
        </div>
    );
};

export default UserInfo;